package com.guhappy.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guhappy.model.user.Company;
import com.guhappy.model.user.GlobalStock;
import com.guhappy.model.user.GlobalStockHome;
import com.guhappy.util.FormatterConverter;
 
/**
 * @author  bduan
 */
public class StockTickerDAO {
    private static final Log log = LogFactory.getLog(StockTickerDAO.class);
    private static final StockTickerDAO stockDAO = new StockTickerDAO();
    private static HashMap<String, GlobalStock> stocks = new HashMap<String, GlobalStock>();
    private static final long TWENTY_MIN = 1200000;
 
    private StockTickerDAO() {}
 
    public static StockTickerDAO getInstance() {
        return stockDAO;
    }
 
    /**
     *
     * @param symbol
     * @return StockBean
     * will return null if unable to retrieve information
     */
    public GlobalStock getStockPrice(String symbol) {
    	GlobalStock stock;
        long currentTime = (new Date()).getTime();
        // Check last updated and only pull stock on average every 20 minutes
        if (stocks.containsKey(symbol)) {
            stock = stocks.get(symbol);
            if(currentTime - stock.getLastUpdated() > TWENTY_MIN) {
                stock = refreshStockInfo(symbol, currentTime);
            }
        } else {
            stock = refreshStockInfo(symbol, currentTime);
        }
        return stock;
    }
 
    //This is synched so we only do one request at a time
    //If yahoo doesn't return stock info we will try to return it from the map in memory
    private synchronized GlobalStock refreshStockInfo(String symbol, long time) {
        try {
        	GlobalStock stockInfo = null;
        	stockInfo = GlobalStockHome.findByTicker(symbol);
        	if (stockInfo == null){
	        	stockInfo = new GlobalStock();
	            Company company = new Company();
	            stockInfo.setCompany(company);
        	}
            URL yahoofin = new URL("http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=svl1oape7drn&e=.csv");
            URLConnection yc = yahoofin.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine;
            while (null !=(inputLine = in.readLine()) ) {
                String[] yahooStockInfo = inputLine.split(",");

                stockInfo.setSticker(yahooStockInfo[0].replaceAll("\"", ""));
                stockInfo.setOutstanding_shares(FormatterConverter.getLong(yahooStockInfo[1]));
                stockInfo.setLast_price(FormatterConverter.getFloat(yahooStockInfo[2]));
                stockInfo.setOpen_price(FormatterConverter.getFloat(yahooStockInfo[3]));
                stockInfo.setCurr_price(FormatterConverter.getFloat(yahooStockInfo[4]));
                stockInfo.setClose_price(FormatterConverter.getFloat(yahooStockInfo[5]));
                stockInfo.setEps(FormatterConverter.getFloat(yahooStockInfo[6]));
                stockInfo.setDividend(FormatterConverter.getFloat(yahooStockInfo[7]));
                stockInfo.setPe_ratio(FormatterConverter.getFloat(yahooStockInfo[8]));
                stockInfo.getCompany().setName(yahooStockInfo[9].replaceAll("\"", ""));
                stockInfo.setChartUrlSmall("http://ichart.finance.yahoo.com/t?s=" + stockInfo.getSticker());
                stockInfo.setChartUrlLarge("http://chart.finance.yahoo.com/w?s=" + stockInfo.getSticker());
                stockInfo.setLastUpdated(time);
                
                GlobalStockHome.attachDirty(stockInfo);
                stocks.put(symbol, stockInfo);
                break;
            }
            in.close();
        } catch (Exception ex) {
            log.error("Unable to get stockinfo for: " + symbol + ex);
        }
        return stocks.get(symbol);
     }
}